#!/usr/bin/env python
# -*- coding: utf-8 -*-

""" 定义 Matlab 代理对象
"""

import pythoncom

class MatlabProxy(object):
    def __init__(self, vim_proxy):
        pythoncom.CoInitialize()
        self.proxy = vim_proxy

    def __del__(self):
        pythoncom.CoUninitialize()

    def is_connected(self):
        try:
            if hasattr(self, '_com'):
                self._com.Execute('pwd')
                return True
            else:
                return False
        except:
            return False

    def connect(self, progid='Matlab.Desktop.Application'):
        try:
            from win32com.client import GetActiveObject
            if not hasattr(self, '_com'):
                self._com = GetActiveObject(progid)
                self.proxy._connected = True
        except:
            from win32com.client import DispatchEx
            self._com = DispatchEx(progid)
            self.proxy._connected = True

    def execute(self, cmd):
        try:
            if hasattr(self, '_com'):
                self._com.Execute(cmd)
        except pywintypes.com_error as e:
            self.proxy._connected = False


